<template>
  <div class="app-container">
    <div
        v-for="(item, index) in tablesList.data"
        :key="item.tableId"
        class="content"
    >
      <el-card
          @dblclick="setting(item,index)"
          class="table-card"
          :class="[
          getStatusInfo(item.status).cardClass,
          { 'table-tennis': index + 1 <= 5 },
          { 'table-mahjong': index + 1 > 5 }
        ]"
          :style="{ animationDelay: `${index * 0.1}s` }"
      >
        <!-- 头部 -->
        <template #header>
          <div class="card-header">
            <div class="table-info">
              <dict-tag
                  :options="table_type"
                  :value="item.status"
                  class="status-tag"
                  :type="getStatusInfo(item.status).tagType"
              />
              <span class="table-number">
                {{ index + 1 <= 5 ? '台球' : '麻将' }}
                {{ item.tableId }}号桌
              </span>
            </div>
            <el-tag :type="getStatusInfo(item.status).priceTagType" class="price-tag">
              单价: ¥{{ item.price }}
            </el-tag>
          </div>
        </template>

        <!-- 主体 -->
        <div class="card-body">
          <div class="info-item">
            <span class="info-label">类型:</span>
            <span class="info-value">{{ index + 1 <= 5 ? '台球桌' : '麻将桌' }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">开台时间:</span>
            <span class="info-value">{{ item.beginTime || '-' }}</span>
          </div>

          <div class="info-item">
            <span class="info-label">运行时长:</span>
            <span class="info-value">{{ item.time || '0分钟' }}</span>
          </div>
          <div class="info-item total-amount">
            <span class="info-label">总金额:</span>
            <span class="info-value">￥{{ item.totalPrice || '0.00' }}元</span>
          </div>
        </div>

        <!-- 底部 -->
        <template #footer>
          <div class="card-footer">
            <span
                class="status-text"
                :style="{ color: getStatusInfo(item.status).statusTextColor }"
            >
              状态: {{ formatStatus(item.status) }}
            </span>
          </div>
        </template>
      </el-card>
    </div>
  </div>

  <el-dialog
      destroy-on-close
      center
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="title"
      v-model="open"
      width="500px"
      append-to-body
  >
    <div class="dialog-content">
      <el-form :model="form" label-width="100px">
        <el-form-item label="桌台类型">
          <el-input v-model="form.tableType" disabled />
        </el-form-item>
        <el-form-item label="桌台编号">
          <el-input v-model="form.tableId" disabled />
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="form.status" disabled placeholder="当前状态">
            <el-option label="使用中" value="1" />
            <el-option label="已预订" value="2" />
            <el-option label="空闲" value="3" />
            <el-option label="维护中" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="运行时长">
          <el-input v-model="form.time" disabled />
        </el-form-item>
        <el-form-item label="消费金额">
          <el-input v-model="form.totalPrice" disabled />
        </el-form-item>
        <el-form-item label="单价/小时">
          <el-input-number :disabled="disable" :min="0" :max="100" :step="0.5" v-model="form.price" placeholder="输入单价" />
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button
            type="primary"
            @click="handleOpen"
            :disabled="isDisabled('open')"
        >
          开台
        </el-button>
        <el-button
            type="info"
            @click="handlejs"
            :disabled="isDisabled('js')"
        >
          结算
        </el-button>
        <el-button
            type="success"
            @click="handleReserve"
            :disabled="isDisabled('reserve')"
        >
          预定
        </el-button>
        <el-button
            type="warning"
            @click="handleMaintain"
            :disabled="isDisabled('maintain')"
        >
          维护
        </el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog  destroy-on-close
              center
              :close-on-click-modal="false"
              :close-on-press-escape="false"
              title="会员信息"
              v-model="members"
              append-to-body>
    <el-form :inline="true" :model="formInline"  class="demo-form-inline" >
      <el-form-item label="用户名">
        <el-input placeholder="请输入用户名"  v-model="formInline.user.fullName" clearable/>
      </el-form-item>
      <el-form-item label="手机号">
        <el-input placeholder="请输入手机号"  v-model="formInline.user.phone" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button @click="search()" type="primary">
          <el-icon><Search/></el-icon>查询
        </el-button>
      </el-form-item>
    </el-form>
    <el-descriptions title="会员信息">
      <el-descriptions-item label="用户名">{{ formInline.user.fullName }}</el-descriptions-item>
      <el-descriptions-item label="电话">{{formInline.user.phone}}</el-descriptions-item>
      <el-descriptions-item label="性别"><dict-tag :options="sys_user_sex" :value="formInline.user.gender"/></el-descriptions-item>
      <el-descriptions-item label="注册日期">
        <el-tag>{{ formInline.user.createTime }}</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="账户状态">
        <dict-tag :options="m_status" :value="formInline.user.status"/>
      </el-descriptions-item>
      <el-descriptions-item label="当前积分">
        {{formInline.user.pointsBalance}}
      </el-descriptions-item>
      <el-descriptions-item label="剩余积分">
        {{formInline.user.balance}}
      </el-descriptions-item>
      <el-descriptions-item label="备注">
        {{formInline.user.remark}}
      </el-descriptions-item>

    </el-descriptions>
    <el-button type="primary" @click="js" >结算</el-button>
  </el-dialog>
</template>
<script setup>
import { listMembers,updateMembers} from "@/api/system/members"
import DictTag from "@/components/DictTag/index.vue";
import { getCurrentInstance, reactive, ref, onMounted,onUnmounted } from "vue";
import { listTables,updateTables } from "@/api/system/tables/index.js";

import {ElMessageBox} from "element-plus";
const disable=ref(false);
const members=ref(false);
const tablesList = reactive({
  data: [],
});
const form = reactive({
  uuid:'',
  tableId: '',
  tableType: '',
  price: '',
  status: '',
  time:'',
  totalPrice:'',
  item:'',
  remark:""

});
const formInline=reactive({
  user:{
    phone:null,
    fullName:null,
    balance:null,
    id:null
  }
})


const { proxy } = getCurrentInstance();
const { m_status, sys_user_sex } = proxy.useDict('m_status', 'sys_user_sex')
const { table_type } = proxy.useDict('table_type');
const open = ref(false);
const title=ref("")
const formatStatus = (status) => {
  const statusMap = {
    "1": '使用中',
    "2": '已预订',
    "3": '空闲',
    "4": '维护中'
  };
  return statusMap[status] || '无状态';
};

const getStatusInfo = (status) => {
  switch (status) {
    case '1':
      return {
        cardClass: 'status-running',
        tagType: 'success',
        priceTagType: 'success',
        statusTextColor: '#67c23a'  // 运行中 → 绿色文字
      };
    case '2':
      return {
        cardClass: 'status-reserved',  // 新增预定中样式类
        tagType: 'primary',            // 蓝色标签
        priceTagType: 'primary',       // 蓝色价格标签
        statusTextColor: '#409eff'     // 预定中 → 蓝色文字
      };
    case '4':
      return {
        cardClass: 'status-maintain',
        tagType: 'warning',
        priceTagType: 'warning',
        statusTextColor: '#e6a23c'  // 维修中 → 橙色文字
      };
    default:
      return {
        cardClass: '',
        tagType: 'info',
        priceTagType: 'info',
        statusTextColor: '#909399'  // 其他 → 灰色文字
      };
  }
};
const  setting = (item, index) => {
  if (item.status === '1') {
    disable.value = true;
  }else {
    disable.value = false
  }
  open.value = true;
  title.value = `${index + 1 <= 5 ? '台球' : '麻将'}${item.tableId}号桌设置`;
  form.tableId = item.tableId;
  form.tableType = index + 1 <= 5 ? '台球桌' : '麻将桌';
  form.price = item.price;
  form.status = item.status;
  form.time = item.time;
  form.totalPrice = item.totalPrice;
  form.uuid= item.uuid;
};
const isDisabled = (action) => {
  const status = form.status; // 当前状态
  // 状态值：1=使用中，2=已预订，3=空闲，4=维护中

  // 使用中
  if (status === '1') {
    // 不能点击维护、预定、开台
    return ['maintain', 'reserve', 'open'].includes(action);
  }

  // 预定
  if (status === '2') {
    // 不能点击维护、预定、结算
    return ['maintain', 'reserve', 'js'].includes(action);
  }

  // 维护中
  if (status === '4') {
    // 不能点击开台、维护、预定
    return ['open', 'maintain', 'reserve'].includes(action);
  }

  // 空闲状态，只有“结算”不能点
  if (status === '3') {
    return action === 'js';
  }

  return false;
};



const handleOpen = () => {

  //开台
  handleSave("1");
};
const search=()=>{
  listMembers(formInline.user).then((res) => {
    if (res.code===200){
      if (res.rows.length===0){
        proxy.$modal.msgWarning("会员不存在")
        formInline.user={
          phone:null,
          fullName:null,
          balance:null,
          id:null
        }
        return;
      }
      formInline.user=res.rows[0];
      formInline.user.balance=res.rows[0].pointsBalance-form.totalPrice;
    }

  })
}
const handlejs = () => {
  if (form.status==="4"){
    open.value = false;
    handleSave("3")
    return;
  }
  //结算
  ElMessageBox.confirm(
      '是否使用会员?',
      '警告',
      {
        confirmButtonText: '是',
        cancelButtonText: '否',
        closeOnClickModal: false,
        type: 'warning',
      }
  )
      .then(() => {
        members.value=true
      })
      .catch(() => {

        ElMessageBox.confirm(
            '请选择支付方式?',
            '警告',
            {
              confirmButtonText: '微信/支付宝',
              cancelButtonText: '现金',
              closeOnClickModal: false,
              type: 'warning',
            }
        )
            .then(() => {

              form.item="微信/支付宝"
              proxy.$modal.msgSuccess({
                type: 'success',
                message: '支付成功',
              })
              handleSave("3");
              form.item=''
            })
            .catch(() => {

              form.item="现金"
              handleSave("3");
              proxy.$modal.msgSuccess({
                type: 'success',
                message: '支付成功',
              })
              form.item=''
            })
      })
};

const handleReserve = () => {
  //预定
  handleSave("2");
};

const handleMaintain = () => {
  //维护
  handleSave("4");
};
const handleSave = (value) => {
  form.status = value;
  updateTables(form).then((res) => {
    if (res.code === 200) {
      setTimeout(()=>{
        getList()
      },1000)

      open.value = false;
    }
  })


};
// 初始化数据
const getList=()=>{
  listTables({ pageNum: 1, pageSize: 10 }).then((res) => {
    tablesList.data = res.rows;
    checkAndUpdateTimer();
  });
}
const js=()=>{
  if (formInline.user.id===null){
    proxy.$modal.msgWarning("请查找会员信息")
    return
  }
  if (formInline.user.status==="1"){
    proxy.$modal.msgError("会员暂时无法使用,请联系管理员!")
    return
  }
  form.status="3"
  form.item="积分"
  updateTables(form).then((res) => {
    if (res.code === 200) {
      setTimeout(()=>{
        getList()
      },1000)

      open.value = false;
      members.value=false
      formInline.user.pointsBalance=formInline.user.balance;

      updateMembers(formInline.user).then((res) => {
        formInline.user={
              phone:null,
              fullName:null,
              balance:null,
              id:null
        }
        form.item=''

      })
    }
  })

}
// 定义定时器变量
// 定时器相关逻辑 - 新增状态检查
const timer = ref(null);

// 检查是否有运行中的项目
const hasRunningItems = () => {
  return tablesList.data.some(item =>
      item.status === '1' || item.status === '2'  // 1=运行中，2=预定中
  );
};
// 启动定时器
const startTimer = () => {
  // 先清除可能存在的定时器，避免重复创建
  if (timer.value) {
    clearInterval(timer.value);
  }

  // 只有存在运行中的项目时才创建定时器
  if (hasRunningItems()) {
    timer.value = setInterval(() => {
      getList();
    }, 5000);
  }
};

// 清除定时器
const clearTimer = () => {
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
};

// 检查并更新定时器状态
const checkAndUpdateTimer = () => {
  if (hasRunningItems()) {
    // 有运行中的项目，确保定时器在运行
    if (!timer.value) {
      startTimer();
    }
  } else {
    // 没有运行中的项目，停止定时器
    clearTimer();
  }
};

// 在组件挂载时初始化数据并检查定时器
onMounted(() => {
  getList();

  // 监听页面可见性变化
  document.addEventListener('visibilitychange', handleVisibilityChange);
});

// 在组件卸载时清除定时器和事件监听
onUnmounted(() => {
  clearTimer();
  document.removeEventListener('visibilitychange', handleVisibilityChange);
});

// 处理页面可见性变化
const handleVisibilityChange = () => {
  if (document.hidden) {
    // 页面不可见时清除定时器
    clearTimer();
  } else {
    // 页面可见时根据状态决定是否启动定时器
    checkAndUpdateTimer();
  }
};
</script>

<style scoped>
/* 基础变量与过渡动画 */
.app-container {
  --bg-color: #f5f7f9;
  --card-bg: #ffffff;
  --text-color: #303133;
  --text-secondary: #8c8c8c;
  --border-color: #f0f0f0;
  --shadow-light: 0 2px 8px rgba(0, 0, 0, 0.08);
  --shadow-hover: 0 6px 16px rgba(0, 0, 0, 0.12);

  padding: 20px;
  background-color: var(--bg-color);
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  justify-content: flex-start;
  transition: background-color 0.5s ease;
}

/* 暗色模式变量 */
.app-container.dark-mode {
  --bg-color: #1a1a2e;
  --card-bg: #16213e;
  --text-color: #e9ecef;
  --text-secondary: #b1b1c1;
  --border-color: #2a2f45;
  --shadow-light: 0 4px 12px rgba(0, 0, 0, 0.4);
  --shadow-hover: 0 8px 24px rgba(0, 0, 0, 0.5);
}

/* 切换按钮 */
.theme-switch {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 100;
  padding: 8px;
  background-color: var(--card-bg);
  border-radius: 4px;
  box-shadow: var(--shadow-light);
  transition: all 0.5s ease;
}

.content {
  flex: 0 0 calc(20% - 16px);
  box-sizing: border-box;
  transition: transform 0.3s ease;
}

.content:hover {
  transform: translateY(-5px);
}

.table-card {
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: var(--shadow-light);
  transition: all 0.5s ease;
  position: relative;
  background-color: var(--card-bg);
  color: var(--text-color);
  opacity: 0;
  transform: translateY(20px);
  animation: fadeInUp 0.6s ease forwards;
}

.table-card:hover {
  box-shadow: var(--shadow-hover);
}

@keyframes fadeInUp {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 运行中样式 */
.status-running {
  border-top: 3px solid #67c23a;
  transition: border-color 0.5s ease;
}
.app-container.dark-mode .status-running {
  border-top-color: #85ce61;
}

.status-running::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  background-color: #67c23a;
  transition: background-color 0.5s ease;
}
.app-container.dark-mode .status-running::before {
  background-color: #85ce61;
}

.status-running .card-header {
  background-color: #f0f9eb;
  border-bottom: 1px solid #e6f4ea;
  transition: all 0.5s ease;
}
.app-container.dark-mode .status-running .card-header {
  background-color: #1b282c;
  border-bottom-color: #2a4044;
}

/* 维修中样式 */
.status-maintain {
  border-top: 3px solid #e6a23c;
  transition: border-color 0.5s ease;
}
.app-container.dark-mode .status-maintain {
  border-top-color: #ebb563;
}

.status-maintain::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  background-color: #e6a23c;
  transition: background-color 0.5s ease;
}
.app-container.dark-mode .status-maintain::before {
  background-color: #ebb563;
}

.status-maintain .card-header {
  background-color: #fdf6ec;
  border-bottom: 1px solid #faecd8;
  transition: all 0.5s ease;
}
.app-container.dark-mode .status-maintain .card-header {
  background-color: #29241b;
  border-bottom-color: #423a27;
}

/* 卡片头部 */
.table-card .card-header {
  background-color: var(--card-bg);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  transition: all 0.5s ease;
}

.table-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.table-number {
  font-weight: 600;
  font-size: 16px;
  color: var(--text-color);
  transition: color 0.5s ease;
}

.status-tag {
  font-size: 12px;
  transition: all 0.5s ease;
}

.price-tag {
  font-size: 12px;
  transition: all 0.5s ease;
}

/* 卡片主体 */
.card-body {
  padding: 16px;
}

.info-item {
  display: flex;
  margin-bottom: 12px;
  font-size: 14px;
  line-height: 1.5;
}

.info-label {
  color: var(--text-secondary);
  min-width: 80px;
  transition: color 0.5s ease;
}

.info-value {
  color: var(--text-color);
  flex: 1;
  transition: color 0.5s ease;
}

.total-amount {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px dashed var(--border-color);
  transition: border-color 0.5s ease;
}

.total-amount .info-value {
  color: #f56c6c;
  font-weight: 600;
  transition: color 0.5s ease;
}
.app-container.dark-mode .total-amount .info-value {
  color: #ff8787;
}
/* 预定中样式 */
.status-reserved {
  border-top: 3px solid #409eff;
  transition: border-color 0.5s ease;
}
.app-container.dark-mode .status-reserved {
  border-top-color: #69b1ff;
}

.status-reserved::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  background-color: #409eff;
  transition: background-color 0.5s ease;
}
.app-container.dark-mode .status-reserved::before {
  background-color: #69b1ff;
}

.status-reserved .card-header {
  background-color: #ecf5ff;
  border-bottom: 1px solid #d9ecff;
  transition: all 0.5s ease;
}
.app-container.dark-mode .status-reserved .card-header {
  background-color: #1d3059;
  border-bottom-color: #2c4a7c;
}
/* 卡片底部 */
.card-footer {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 12px 16px;
  background-color: rgba(0, 0, 0, 0.02);
  border-top: 1px solid var(--border-color);
  transition: all 0.5s ease;
}
.app-container.dark-mode .card-footer {
  background-color: rgba(0, 0, 0, 0.15);
}

.status-text {
  font-size: 14px;
  transition: color 0.5s ease;
}

/* 响应式 */
@media screen and (max-width: 1200px) {
  .content {
    flex: 0 0 calc(25% - 15px);
  }
}
@media screen and (max-width: 992px) {
  .content {
    flex: 0 0 calc(33.33% - 13px);
  }
}
@media screen and (max-width: 768px) {
  .content {
    flex: 0 0 calc(50% - 10px);
  }
}
@media screen and (max-width: 576px) {
  .content {
    flex: 0 0 100%;
  }

  .theme-switch {
    top: 10px;
    right: 10px;
  }
}
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
